<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>layui</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <link rel="stylesheet" href="/lib/layui-v2.6.3/css/layui.css" media="all">
    <link rel="stylesheet" href="/css/public.css" media="all">
</head>
<style>
    .layui-form input[type=checkbox]{
        display: inline-block !important;
    }
    .layui-form-checkbox{
        display: none !important;
    }
</style>
<body>
<div class="layuimini-container">
    <div class="layuimini-main">

        <fieldset class="table-search-fieldset">
            <legend>搜索信息</legend>
            <div style="margin: 10px 10px 10px 10px">
                <form class="layui-form layui-form-pane" action="">
                    <div class="layui-form-item">
                        <div class="layui-inline">
                            <label class="layui-form-label">角色</label>
                            <div class="layui-input-inline">
                                <select name="role" lay-verify="required">
                                    <option value="-1" selected>全部</option>
                                    <option value="1">管理员</option>
                                    <option value="0">普通角色</option>
                                </select>
                            </div>

                        </div>
                        <div class="layui-inline">
                            <label class="layui-form-label">账号</label>
                            <div class="layui-input-inline">
                                <input type="text" name="username" autocomplete="off" class="layui-input">
                            </div>
                        </div>
                        <div class="layui-inline">
                            <button type="submit" class="layui-btn layui-btn-primary"  lay-submit lay-filter="data-search-btn"><i class="layui-icon"></i> 搜 索</button>

                        </div>
                    </div>
                </form>

            </div>
        </fieldset>

        <button data-modal-action="open" data-modal-target="myModal"   class="layui-btn layui-btn-normal" >添加</button>


        <table class="layui-hide" id="currentTableId" lay-filter="currentTableFilter"></table>

        <script type="text/html" id="currentTableBar">
            <a class="layui-btn layui-btn-normal layui-btn-xs data-count-edit" lay-event="edit">编辑</a>
            <a class="layui-btn layui-btn-xs layui-btn-danger data-count-delete" lay-event="delete">删除</a>
        </script>

    </div>
</div>




<div id="myModal" class="modal">
    <div class="modal-content modal-normal">
        <span class="close">&times;</span>

        <div class="layui-form layuimini-form">
            <div class="layui-form-item">
                <input id="id" style="display: none">
                <label class="layui-form-label"><span style="font-weight: bold">账号</span><span style="color: red">*</span></label>
                <div class="layui-input-block">
                    <input type="text" name="username" id="username" placeholder="请输入账号"  class="layui-input">
                </div>
            </div>

            <div class="layui-form-item">
                <label class="layui-form-label"><span style="font-weight: bold">密码</span><span style="color: red">*</span></label>
                <div class="layui-input-block">
                    <input type="text" name="password"  id="password" placeholder="请输入密码" class="layui-input">
                </div>
            </div>

            <div class="layui-form-item">
                <label class="layui-form-label"><span style="font-weight: bold">角色</span><span style="color: red">*</span></label>
                <div class="layui-input-block">
                    <input type="radio" name="role" lay-filter="role" value="0" title="普通用户" checked="">
                    <input type="radio" name="role" lay-filter="role" value="1" title="管理员">
                </div>
            </div>


            <div class="layui-form-item"  id="permissionId">
                <label class="layui-form-label"><span style="font-weight: bold">权限</span><span style="color: red">*</span></label>
                <div >
                    <label th:each="permission:${actuatorList}" style="float: left;width: 60%">
                        <input   name="permission"
                               type="checkbox" th:value="${permission.id}" th:text="${permission.title}+'('+${permission.appName}+')'" >
                        <br>
                    </label>
                </div>
            </div>
            <div class="layui-form-item">
                <div class="layui-input-block">
                    <button class="layui-btn layui-btn-normal" onclick="saveUser()" >保  存</button>
                    <button class="layui-btn layui-btn-primary" onclick="cancelBtn()">取  消</button>
                </div>
            </div>
        </div>
    </div>
</div>
<script src="/lib/layui-v2.6.3/layui.js" charset="utf-8"></script>
<script src="/plugins/cronGen/jquery-2.1.4.min.js"></script>
<script>


    layui.use(['form', 'table'], function () {
        var $ = layui.jquery,
            form = layui.form,
            table = layui.table;

        table.render({
            elem: '#currentTableId',
            url: '/user/pageList',
            method: 'post',
            where:{role:$("select[name='role']").val(),username:$("input[name='username']").val()},
            parseData: function (res) {
                return {
                    "code": res.code, //解析接口状态
                    "msg": res.message, //解析提示文本
                    "count": res.recordsTotal, //解析数据长度
                    "data": res.data //解析数据列表
                };
            },
            cols: [
                [
                {field: 'username',title: '账号'},
                {field: 'role', title: '角色',
                    templet: function ( d) {
                        if (d.role==1) {
                            return '管理员';
                        } else {
                            return '普通用户';
                        }
                    }
                },
                {title: '操作', minWidth: 90, toolbar: '#currentTableBar', align: "center"}
             ]
            ],
            limits: [10, 15, 20, 25, 50, 100],
            pageSize: 15,
            page: true,
             request: {
                pageName: 'page',
                limitName: 'rows'
            } ,
            skin: 'line'
        });
        form.on("radio(role)", function (data) {
            var role = data.value;
            if (this.value == '0') {
                document.getElementById("permissionId").style.display="block";
            } else if (this.value == '1') {
                document.getElementById("permissionId").style.display="none";
                $('input[name="permission"]').each(function(){
                    $(this).prop('checked', false);
                });
            }
           } );
            // 监听搜索操作
        form.on('submit(data-search-btn)', function (data) {
            //执行搜索重载
            table.reload('currentTableId', {
                page: {
                    curr: 1
                }
                , where: data.field
            }, 'data');

            return false;
        });

        /**
         * toolbar监听事件
         */
        table.on('toolbar(currentTableFilter)', function (obj) {
            if (obj.event === 'add') {  // 监听添加操作
                var index = layer.open({
                    title: '新增执行器',
                    type: 2,
                    shade: 0.2,
                    maxmin:true,
                    shadeClose: true,
                    area: ['50%', '60%'],
                    content: '/job_actuator/add',
                });
                $(window).on("resize", function () {
                    layer.full(index);
                });
            } else if (obj.event === 'delete') {  // 监听删除操作
                var checkStatus = table.checkStatus('currentTableId')
                    , data = checkStatus.data;
                layer.alert(JSON.stringify(data));
            }
        });

        //监听表格复选框选择
        table.on('checkbox(currentTableFilter)', function (obj) {
            console.log(obj)
        });

        table.on('tool(currentTableFilter)', function (obj) {
            var data = obj.data;
            if (obj.event === 'edit') {
                var targetModal = document.getElementById('myModal');
                openModalEdit(targetModal,data,form);
            } else if (obj.event === 'delete') {
                layer.confirm( '确认删除？' , {
                    icon: 3,
                    title: '系统提示' ,
                    btn: [ '确定', '取消' ]
                }, function(index){
                    layer.close(index);
                    $.ajax({
                        url: '/user/remove',
                        type: 'POST',
                        data : {
                            "id" : data.id
                        },
                        dataType : "json",
                        success: function (res) {
                            console.log('----------back------ddddddd',res)
                            if (res.code == "200") {
                                layer.alert('删除成功', {
                                    time: 1*1000
                                    ,success: function(layero, index){
                                        var timeNum = this.time/1000, setText = function(start){
                                            layer.title((start ? timeNum : --timeNum) + ' 秒后关闭', index);
                                        };
                                        setText(!0);
                                        this.timer = setInterval(setText, 1000);
                                        if(timeNum <= 0) clearInterval(this.timer);
                                        table.reload('currentTableId', {
                                            page: {
                                                curr: 1
                                            }
                                            , where: data.field
                                        }, 'data');
                                    }
                                    ,end: function(){
                                        clearInterval(this.timer);
                                        layer.close(index);
                                        var iframeIndex = parent.layer.getFrameIndex(window.name);
                                        parent.layer.close(iframeIndex);
                                        window.parent.reload();
                                    }
                                });
                            } else {
                                layer.open({
                                    title: res.message,
                                    btn: [ '确认' ],
                                    content: (res.message || '删除失败' ),
                                    icon: '2'
                                });
                            }

                        },
                        error: function (error) {

                        }
                    })

                });
            }else if (obj.event === 'addressList') {
                var html = '<div>';
                if (data.registryList) {
                    for (var index in data.registryList) {
                        html += (parseInt(index)+1) + '. <span class="badge bg-green" >' + data.registryList[index] + '</span><br>';
                    }
                }
                html += '</div>';

                layer.open({
                    title: '注册节点' ,
                    btn: [ '确定' ],
                    content: html
                });
            }
        });
        form.render();
    });


    function reload() {
        location.reload();
    }


    // 获取触发模态框的自定义属性
    var modalButtons = document.querySelectorAll("[data-modal-action]");

    // 获取模态框主体
    var modals = document.querySelectorAll(".modal");

    function cancelBtn(){
        var targetModal = document.getElementById('myModal');
        closeModal(targetModal);
    }

    // 关闭模态框
    function closeModal(modal) {
        modal.querySelector(".modal-content").classList.add("modal-hide");
        modal.querySelector(".modal-content").addEventListener("animationend", function () {
            modal.style.display = "none";
        }, { once: true });
    }
    // 监听模态框的按钮事件
    modalButtons.forEach(function(button) {
        button.addEventListener("click", function() {
            var targetId = this.dataset.modalTarget;
            var targetModal = document.getElementById(targetId);

            if (targetModal) {
                var action = this.dataset.modalAction;
                if (action === "open") {
                    $('input[id="username"]').val(undefined);
                    $('input[id="password"]').val(undefined);
                    $('input[id="id"]').val(undefined);
                    $('input[name="role"]').each(function(){
                        $(this).prop('checked', false);
                    });

                    $('input[name="permission"]').each(function(){
                        $(this).prop('checked', false);
                    });
                    openModal(targetModal);
                } else if (action === "close") {
                    closeModal(targetModal);
                }
            }
        });
    });

    // 打开模态框
    function openModal(modal) {
        modal.style.display = "block";
        modal.querySelector(".modal-content").classList.remove("modal-hide");
    }
    // 监听模态框的关闭时事件
    modals.forEach(function(modal) {
        var closeButton = modal.querySelector(".close");
        if (closeButton) {
            closeButton.addEventListener("click", function() {
                var targetModal = this.closest(".modal");
                closeModal(targetModal);
            });
        }
    });
    // 当用户点击模态框外部时，关闭模态框
    window.onclick = function (event) {
        modals.forEach(function(modal) {
            if (event.target === modal) {
                closeModal(modal);
            }
        });
    };


    function  saveUser(){
        var id  = $('input[id="id"]').val();
        var username  = $('input[id="username"]').val();
        var password  = $('input[id="password"]').val();
        var role  = $('input[name="role"]:checked').val();
        var permissionArr = [];
        $('input[name="permission"]:checked').each(function(){
            permissionArr.push($(this).val());
        });
        var data = {
            username:username,
            password:password,
            role:role,
            id:id,
            permission:permissionArr.join(',')
        }
        var url = '/user/add';
        if (id!=undefined&&id!='') {
            url =  '/user/update';
        }
        $.ajax({
            url: url,
            type: 'post',
            async: false,
            data:JSON.stringify(data),
            contentType: 'application/json;charset=UTF-8',
            success: function (response) {

                if (response.code=="200"){
                    layer.alert('保存成功', {
                        time: 1*1000
                        ,success: function(layero, index){
                            var timeNum = this.time/1000, setText = function(start){
                                layer.title((start ? timeNum : --timeNum) + ' 秒后关闭', index);
                            };
                            setText(!0);
                            this.timer = setInterval(setText, 1000);
                            if(timeNum <= 0) clearInterval(this.timer);
                            location.reload();
                            cancelBtn();

                        }
                        ,end: function(){
                            clearInterval(this.timer);
                            layer.close(index);
                            var iframeIndex = parent.layer.getFrameIndex(window.name);
                            parent.layer.close(iframeIndex);
                            window.parent.reload();
                        }
                    });
                }else if (response.code=="500"){
                    layer.msg(response.message, {
                        offset: 'd',
                        anim: 1
                    });
                    layer.close(index);
                }



            },
            error: function (error) {
                console.log(1234566);
                console.log('error',error)
                layer.alert(error.responseJSON.message)
                layer.close(index);
            }
        })
    }

    function openModalEdit(modal,data,form) {
         $('input[id="username"]').val(data.username);
         $('input[id="password"]').val(data.password);
         $('input[id="id"]').val(data.id);
         if (data.role == '1') {
             document.getElementById("permissionId").style.display="none";
             $('input[name="permission"]').each(function(){
                 $(this).prop('checked', false);
             });
         }
         $('input[name="role"]').each(function(){
            if(data.role == $(this).val()){
                $(this).prop('checked', true);
            }else{
                $(this).prop('checked', false);
            }
        });

        $('input[name="permission"]').each(function(){

            if(data.permission.indexOf($(this).val())!=-1){
                $(this).prop('checked', true);
            }else{
                $(this).prop('checked', false);
            }
        });
        console.log('----datadatadata---------',data)

        form.render();
        modal.style.display = "block";
        modal.querySelector(".modal-content").classList.remove("modal-hide");
    }
</script>
<style>
    /*模态框主体样式*/
    .modal {
        display: none;
        position: fixed;
        z-index: 1;
        left: 0;
        top: 0;
        width: 100%;
        height: 100%;
        overflow: auto;
        background-color: rgba(0, 0, 0, 0.5);
    }

    /*模态框公共样式*/
    .modal-content {
        background-color: #fefefe;
        margin: 50px auto 0;
        padding: 20px;
        border: 1px solid #888;
        box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2);
        animation: modal-show 0.3s;
    }

    /* 正常大小 */
    .modal-normal {
        width: 1000px;
    }

    /* 中等大小 */
    .modal-medium {
        width: 400px;
    }

    /* 迷你大小 */
    .modal-mini {
        width: 250px;
    }

    /* 隐藏 */
    .modal-hide {
        animation: modal-hide 0.3s;
    }

    /* 展示动画 */
    @keyframes modal-show {
        from {
            opacity: 0;
            transform: translateY(-50px);
        }
        to {
            opacity: 1;
            transform: translateY(0);
        }
    }

    /* 隐藏动画 */
    @keyframes modal-hide {
        from {
            opacity: 1;
            transform: translateY(0);
        }
        to {
            opacity: 0;
            transform: translateY(-50px);
        }
    }

    /*关闭按钮*/
    .close {
        color: #aaa;
        float: right;
        font-size: 28px;
        font-weight: bold;
        cursor: pointer;
        margin-bottom: 12px;
        -webkit-tap-highlight-color: rgba(255,0,0,0);
    }

    /*关闭按钮的鼠标点击和经过样式*/
    .close:hover,
    .close:focus {
        color: black;
        text-decoration: none;
        cursor: pointer;
        -webkit-tap-highlight-color: rgba(255,0,0,0);
    }
</style>
</body>
</html>